import axios from 'axios'
import store from '../store'
import { Message } from 'element-ui'
import { getToken } from './auth'

const instance = axios.create({
  responseType: 'json',
  timeout: 15000
})

instance.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['token'] = getToken()
  }
  return config
}, err => {
  return Promise.reject(err)
})

instance.interceptors.response.use(response => {
  return response.data
}, error => {
  Message({
    message: error.response.data.msg,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error.response)
})

export default instance
